<template>
  <div class="traceability-tabs">
    <div class="traceability-list">
      <!-- 顶部操作栏 -->
      <div class="toolbar">
       <el-form :inline="true" :model="can" class="demo-form-inline">
        <el-form-item label="生产批次">
          <el-input v-model="can.Batch" placeholder="生产批次" clearable />
        </el-form-item>
        <el-form-item label="请选择商品" prop="region">
          <el-select v-model="can.Sid" placeholder="请选择商品"  clearable >
            <el-option v-for="a in goodsData" :label="a.goodsName" :value="a.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="toolbar-btn" @click="gettableData">查询</el-button>
          <el-button type="primary" class="toolbar-btn" @click="opensTrace(null,'基本信息')"><el-icon><Plus /></el-icon><span>新 增</span></el-button>
          <el-button type="danger" class="toolbar-btn" @click="rangDel()"><el-icon><DeleteFilled /></el-icon><span>删 除</span></el-button>
        </el-form-item>
      </el-form>
      </div>
      <!-- 商品表格 -->
      <el-table
        :data="tableData"
        ref="tableRef"
        border
        class="custom-table"
        style="width: 100%; margin-top: 12px; border-radius: 12px; overflow: hidden;height: 450px;"
        :header-cell-style="{ background: '#f8f9fb', color: '#222', fontWeight: 'bold', fontSize: '16px' }"
        :row-style="{ height: '52px', fontSize: '15px' }"
        @selection-change="handleSelectionChange()"
        highlight-current-row
      >
        <el-table-column type="selection"  width="50" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="goodsName" label="商品名称" width="140" align="center" />
        <el-table-column prop="batch" label="生产批次" width="120" align="center" />
        <el-table-column prop="shelfLife" label="保质期（天）" width="130" align="center" />
        <el-table-column prop="licenseNumber" label="生产许可证号" width="180" align="center" />
        <el-table-column prop="manufacturers" label="生产企业" width="260" align="center" />
        <el-table-column prop="perfection" label="信息完整度" width="120" align="center">
          <template #default="scope">
            <span :style="{color: getIntegrityColor(scope.row.perfection), fontWeight: 'bold', fontSize: '15px'}">
              {{ scope.row.perfection }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="onDetail(scope.row)">详情</el-button>
            <el-button link type="primary" style="margin-left:18px;" @click="opensTrace(scope.row,'修改')">修改</el-button>
            <el-button link type="primary" @click="handleDownload(scope.row)">导出溯源码</el-button>
            <el-button link type="primary" style="margin-left:18px;" @click="onDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="demo-pagination-block" style="margin-top: 20px;">
        <el-pagination
          v-model:current-page="page.PageIndex"
          v-model:page-size="page.PageSize"
          prev-text="上一页"
          next-text="下一页"
          :page-sizes="[15, 20, 25, 30]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.listcount"
        />
      </div>
    </div>
  </div>

<!-- 添加/修改对话框 -->
 <el-dialog v-model="logic.opens" :title="logic.titles" width="600" center>
    <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="auto"
        @submit.prevent="handleSubmit"
      >
        <el-form-item label="请选择商品" prop="region">
          <el-select v-model="form.sid" placeholder="请选择商品">
            <el-option v-for="a in goodsData" :label="a.goodsName" :value="a.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="生产批次" prop="batch">
          <el-input 
            v-model="form.batch" 
            placeholder="请输入生产批次"
          />
        </el-form-item>
        
        <el-form-item label="保质期（天）" prop="shelfLife">
          <el-input 
            v-model="form.shelfLife" 
            placeholder="请输入保质期"
          />
        </el-form-item>
        
        <el-form-item label="生产许可证号"  prop="licenseNumber">
          <el-input 
            v-model="form.licenseNumber" 
            placeholder="请输入生产许可证号"
          />
        </el-form-item>
        
        <el-form-item label="生产企业" prop="manufacturers">
          <el-input 
            v-model="form.manufacturers" 
            placeholder="生产企业"
          />
        </el-form-item>
        <el-form-item label="封面图"  prop="coverImageUrl">
          
          <el-upload
            class="avatar-uploader"
            action="http://10.223.8.24:8023/api/FileUpload/UploadFile"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.coverImageUrl" :src="form.coverImageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit()" :loading="loading">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { onMounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'
import type { ElTable, UploadProps } from 'element-plus'
import { trance } from '@/Helper/axiosSetting'
import moment from 'moment'
import { qrcanvas } from 'qrcanvas';
const router = useRouter()

onMounted(()=>{
    getGoodData()
  gettableData()
})

//获取基本信息列表
const tableData = ref([])
const can=reactive({
  Sid:null,
  Batch:''
})
const page=reactive({
  PageIndex:1,
  PageSize:15,
  listcount:0
})
watch(page,()=>{
  gettableData()
})
const gettableData=()=>{
  trance.get("api/Tranc/GetTraceabilityList",{params:{
    Sid:can.Sid,
    Batch:can.Batch,
    PageIndex:page.PageIndex,
    PageSize:page.PageSize
  }}).then(res=>{
    tableData.value=res.data.data.list
    page.listcount=res.data.data.recordCount
  })
}





//实例表组件
const tableRef = ref<InstanceType<typeof ElTable> | null>(null)

//获取ID
const handleSelectionChange = () => {
   // 可以在这里进行其他操作，比如删除选中的行
   logic.ids=[] 
  console.log('通过方法获取的选中行：', tableRef.value?.getSelectionRows())
  tableRef.value?.getSelectionRows().forEach((x:any) => {
    logic.ids.push(x.id)
  });
  logic.nums=JSON.stringify(tableRef.value?.getSelectionRows())
}
//批量删除
const rangDel=()=>{
  
  ElMessageBox.confirm(
    '确认删除已选中的'+logic.ids.length+'个溯源商品信息?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      if(logic.ids.length==0){
        ElMessage.info("至少选中一项信息")
        return;
      }
      trance.get("api/Tranc/RangeDel",{params:{json:logic.nums}}).then(res=>{
        if(res.data.code==200){
          ElMessage.success(res.data.message)
          gettableData();
        }else{
          ElMessage.error("删除失败")
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}


function getIntegrityColor(val: string) {
  if (val === '100%') return 'green'
  if (val === '80%') return 'orange'
  return 'red'
}
//跳转到详情
function onDetail(row: any) { router.push({ path: '/TraceabilityDetailView', query: {id:row.id} }) }







//新增对话框
const loading = ref(false)
const formRef = ref<FormInstance>()


// 表单验证规则
const formRules = reactive<FormRules>({
  batch: [
    { required: true, message: '请输入生产批次', trigger: 'blur' },
    { min: 0, max: 30, message: '生产批次最多30个字符', trigger: 'blur' }
  ],
  shelfLife: [
    { required: true, message: '保质期不能为空', trigger: 'blur' },
    // { min: 0, max: 5, message: '保质期最多5个字符', trigger: 'blur' }
  ],
  licenseNumber: [
    { required: true, message: '请输入生产许可证号', trigger: 'blur' },
    { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/, message: '只允许输入数字、字母（包括大写、小写）', trigger: 'blur' }
  ],
  manufacturers: [
    { required: true, message: '请输入生产企业', trigger: 'blur' },
    { min: 0, max: 30, message: '最多30个字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '只允许输入数字、字母（包括大写、小写）', trigger: 'blur' }
  ],
  coverImageUrl: [
    { required: true, message: '请上传封面图片', trigger: 'blur' },
  ],
})
//基本信息实体
const form=reactive({
  "sid": null,
  "batch": "",
  "shelfLife": '',
  "licenseNumber": "",
  "manufacturers": "",
  "coverImageUrl": "",
  "isUpdateOrDel":false
})



//对话框中间实体
const logic = reactive({
  opens: false,
  titles: '',
  nums: '',
  ids: [] as (number | string)[],
})
//打开对话框
const opensTrace=(row:any,titles:string)=>{
  logic.opens=true
  logic.titles=titles

  if(titles=='基本信息'){
    form.batch=moment().format("YYYYMMDD").toString()
    form.coverImageUrl="",
    form.licenseNumber="",
    form.manufacturers="",
    form.shelfLife='',
    form.sid=null
  }else{
    Object.assign(form,row);
  }
  
  
}

//商品信息
const goodsData=ref<any>([])
const getGoodData=()=>{
  trance.get("api/Tranc/GetGoodsList").then(res=>{
    goodsData.value=res.data.data
  })
}

//图片上传
const handleAvatarSuccess = (proj:any) => {
  console.log(proj)
  form.coverImageUrl=proj;
}
//图片的格式验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // if (rawFile.type !== 'image/jpeg') {
  //   ElMessage.error('Avatar picture must be JPG format!')
  //   return false
  // } else if (rawFile.size / 1024 / 1024 > 2) {
  //   ElMessage.error('Avatar picture size can not exceed 2MB!')
  //   return false
  // }
  return true
}
//（单删）删除基本信息
const onDelete=(row: any)=>{
   ElMessageBox.confirm(
    '确认删除该溯源商品信息?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      trance.post("api/Tranc/TraceabilityEadit",row).then(res=>{
        if(res.data.code==200){
          ElMessage.success(res.data.message)
          gettableData();
        }else{
          ElMessage.error("删除失败")
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//添加/修改基本信息
const saveinfo=()=>{
  if(logic.titles=="修改"){
    form.isUpdateOrDel=true
    trance.post("api/Tranc/TraceabilityEadit",form).then(res=>{
    if(res.data.code==200){
      ElMessage.success(res.data.message)
      gettableData();
      logic.opens=false
    }else{
      ElMessage.error(res.data.message)
    }
  })
  }else{
    trance.post("api/Tranc/AddTraceability",form).then(res=>{
    if(res.data.code==200){
      ElMessage.success("保存成功")
      gettableData();
      logic.opens=false
    }else{
      ElMessage.error(res.data.message)
    }
  })
  }
  
  
}


// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) {
    ElMessage.error('表单实例未初始化')
    return
  }
  
  try {
    loading.value = true
    
    // 关键：使用 await 等待验证完成
    const valid = await formRef.value.validate()
    
    if (valid) {
      // 验证通过，执行提交逻辑
      console.log('表单数据:', form)
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))
      saveinfo()

    } else {
      // 验证失败
      ElMessage.error('请检查表单填写是否正确')
    }
  } catch (error) {


  } finally {
    loading.value = false
  }
}




//获取溯源码



// const canvas = qrcanvas({
//   data: 'http://10.223.8.21:8081/'
// });

// 保存图片
function saveFile(strData: any, fileType: any, fileName = "name") {
    let saveLink = document.createElement("a");//创建a链接
    saveLink.download = fileName + "." + fileType;//设置下载的文件名和类型
    saveLink.href = strData;//设置下载链接
    saveLink.click();//点击下载
}
function handleDownload(row: any) {
  // 1. 拼接二维码内容
  const url = `http://10.223.8.21:8081/TraceabilityDetailView?id=${row.id}`;
  // 2. 生成二维码
  // 生成canvas实例
  const canvas = qrcanvas({
    data: url
  });
  // 3. 转为图片并下载
  // canvas转为dataURL(dase64)
  const dateUrl = canvas.toDataURL();
  saveFile(dateUrl, 'png', `溯源项目_${row.id}`);
}


</script>

<style scoped>
.traceability-tabs {
  background: #f4f6fa;
  padding: 32px 0 0 0;
  min-height: 100vh;
}
.traceability-list {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.07);
  padding: 32px 32px 24px 32px;
  min-height: 600px;
}
.toolbar {
  display: flex;
  gap: 24px;
  margin-bottom: 18px;
}
.toolbar-btn {
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  padding: 0 28px;
  height: 40px;
  box-shadow: 0 2px 8px rgba(64,158,255,0.08);
}
.custom-table .el-table__header th {
  font-weight: bold;
  background: #f8f9fb;
  color: #222;
  font-size: 16px;
}
.custom-table .el-table__row {
  font-size: 15px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
}

</style>
<style>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
